package com.df.gameserver.net.websocket;

import com.df.gameserver.net.websocket.handler.NioWebSocketChannelInitializer;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

@Slf4j
@Component
public class WebSocketServer extends Thread {
    NioEventLoopGroup boss = new NioEventLoopGroup();
    NioEventLoopGroup work = new NioEventLoopGroup();
    ChannelFuture channelFuture;

    ServerBootstrap bootstrap;

    @PostConstruct
    void init() {
        bootstrap = new ServerBootstrap();
        bootstrap.group(boss, work);
        bootstrap.channel(NioServerSocketChannel.class);
        bootstrap.childHandler(new NioWebSocketChannelInitializer());
    }

    @Override
    public void run() {

        try {
            channelFuture = bootstrap.bind(8090).sync();
            log.info("webSocket服务器启动成功");
        } catch (InterruptedException e) {
            e.printStackTrace();
            System.exit(-1);
        }

    }

    @PreDestroy
    public void stopServer() {
        try {
            channelFuture.channel().closeFuture().sync();
            log.info("websocket服务器已关闭");
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            boss.shutdownGracefully();
            work.shutdownGracefully();
        }
    }
}
